package com.zm.campus.exceptions;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zm.campus.pojo.RespBean;
import com.zm.campus.pojo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOError;
import java.io.IOException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)//整个要处理的异常类
    public RespBean ExceptionHandler(Exception e){


            if (e instanceof GlobalException){//如果当前异常属于GlobalException(它继承运行时异常类)，则返回对应的错误
                GlobalException ex=(GlobalException)e;
                return RespBean.error(ex.getRespBeanEnum());
            }else if (e instanceof BindException){//我们自定义参数校验注解里面抛的异常就是这个BindException
                BindException ex=(BindException)e;
                RespBean respBean=RespBean.error(RespBeanEnum.BIND_ERROR);
                respBean.setMessage(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
                return respBean;
            }else if (e instanceof BlockException){
                return RespBean.error(RespBeanEnum.doServiceBusy);
            }else if (e instanceof IOException){
                return RespBean.error(RespBeanEnum.IOError);
            }
            //如果都不属于以上异常则是
        return RespBean.error(RespBeanEnum.ERROR);
    }

}
